<template>
  <div class="app-container">
    <!-- <el-button type="text" @click="dialogVisible = true">添加</el-button> -->
    <!-- <el-card shadow="never"> -->
    <!-- <div slot="header" style="text-align: center;">店铺列表</div> -->
    <!-- 店铺店铺列表-->
    <el-button type="success" @click="addmodel">添加</el-button>
    <div class="tableClass">
      <el-table :data="formdata" v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}" border
        style="width: 100%;">
        <el-table-column align="center" prop="id" label="序号" />
        <el-table-column align="center" prop="display_name" label="角色名称" />
        <el-table-column align="center" prop="description" label="角色描述">
          <template slot-scope="scope">
            <span v-if="scope.row.description != null ">{{scope.row.description}}</span>
            <span v-else style="color: red;">暂无描述</span>
          </template>
        </el-table-column>

        <!-- <el-table-column align="center" prop="display_name" label="角色权限" /> -->
        <el-table-column label="操作" align="center" width="230px">
          <template slot-scope="scope">
            <!-- scope.row 获取整行信息 表示当前单元格 #ff9900ba-->
            <el-button class="btnAppeal" size="small" type="warning" @click="updateMsg(scope.row)">修改</el-button>
            <el-button class="btnAppeal" size="small" type="danger" @click="delMsg(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <!-- 分页 -->
      <div style="text-align: center;">
        <el-pagination background layout="prev, pager, next" @current-change="pageChange" :page-size="pageSize" :total="totalusers" />
      </div>
    </div>
    <!-- </el-card> -->


    <!-- 添加模态款 -->
    <el-dialog :title="title" :visible.sync="modelMsg">
      <div class="msgDiv">
        <!-- <h3>店铺基础信息</h3> -->
        <div>
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item v-show="vshow" label="序号">
              <el-input v-model="form.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="角色名称" :required="true">
              <el-input v-model="form.display_name" placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="form.description" placeholder="请输入角色描述"></el-input>
            </el-form-item>
            <!-- <el-form-item label="角色权限" :required="true">
              <el-input v-model="form.display_name" placeholder="请输入角色权限"></el-input>
            </el-form-item> -->
            <el-form-item label="选择权限" :required="true">
              <div style="text-align: left;">
                <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>

                <el-checkbox-group v-model="checkedRoles" @change="CheckedRolesChange">


                  <div>
                    <el-checkbox v-for="role in aboutList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>

                  <div>
                    <el-checkbox v-for="role in areaList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>

                  <div>
                    <el-checkbox v-for="role in orderList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in roleListAll" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in adminList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>

                  <div>
                    <el-checkbox v-for="role in buttonList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in bannerList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in discountList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in data_summary_select" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                    <el-checkbox v-for="role in money_change_select" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                    <el-checkbox v-for="role in permission_select" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in authorizeList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in enterpriseList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in merchantList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in goodsList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in advertList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in distributorList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in distributionList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in withdrawList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                  <div>
                    <el-checkbox v-for="role in commissionList" :key="role.id" :label="role">
                      {{ role.display_name }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
            </el-form-item>

            <el-button type="success" @click="addMsg(form)">{{addORupdate}}</el-button>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        modelMsg: false,
        form: {
          id: "",
          display_name: "",
          description: "",
          permission_id: []
        },
        vshow: false,
        loading: false,
        title: "",
        addORupdate: "",
        formdata: [],
        rolesList: [],
        checkedRoles: [],
        checkAll: false,
        totalusers: 0, //总行数
        pageSize: 5, //每页几行
        startpage: 1, //起始页
        authorizeList: [],
        goodsList: [],
        distributionList:[],
        distributorList:[],
        withdrawList:[],
        commissionList:[],
        discountList: [],
        data_summary_select: [],
        money_change_select: [],
        merchantList: [],
        permission_select: [],
        adminList: [],
        roleListAll: [],
        aboutList: [],
        areaList: [],
        buttonList: [],
        orderList: [],
        enterpriseList: [],
        bannerList:[],
        advertList:[]
      }
    },
    mounted() {
      this.roleList()
      this.permissionsList()
    },
    methods: {

      permissionsList() {
        let params = {
          "page": 1,
          "limit": 100000
        }
        this.$api.permissionsList(params).then(res => {
          console.log(res)
          if (res.data.level == "success") {
            this.rolesList = res.data.data
            this.rolesList.forEach(item => {
              this.searchName("authorize", this.authorizeList, item)
              this.searchName("goods", this.goodsList, item)
              this.searchName("discount", this.discountList, item)
              this.searchName("data_summary_select", this.data_summary_select, item)
              this.searchName("money_change_select", this.money_change_select, item)
              this.searchName("merchant", this.merchantList, item)
              this.searchName("permission_select", this.permission_select, item)
              this.searchName("admin", this.adminList, item)
              this.searchName("role", this.roleListAll, item)
              this.searchName("about", this.aboutList, item)
              this.searchName("area", this.areaList, item)
              this.searchName("button", this.buttonList, item)
              this.searchName("order", this.orderList, item)
              this.searchName("enterprise", this.enterpriseList, item)
              this.searchName("banner", this.bannerList, item)
              this.searchName("distribution", this.distributionList, item)
              this.searchName("distributor", this.distributorList, item)
              this.searchName("withdraw", this.withdrawList, item)
              this.searchName("commission", this.commissionList, item)
              this.searchName("advert", this.advertList, item)



            })
          } else {
            this.$message.error(res.data.message)
          }
        })
      },
      //search检索关键词分类
      searchName(searchName, everyList, item) {
        if (item.name.search(searchName) != -1) {
          everyList.push(item)
        }
      },
      /* 全选权限 */
      handleCheckAllChange(val) {
        // 判断数组是否有相同数字或字符，有返回true。正则表达式
        Array.prototype.in_array = function(e) {
          var r = new RegExp(',' + e + ',')
          return (r.test(',' + this.join(this.S) + ','))
        }
        /* 三元表达式 */
        this.checkedRoles = val ? this.rolesList : []
        for (let i = 0; i < this.checkedRoles.length; i++) {
          const roleid = this.checkedRoles[i].id
          // 判断权限数组里是否存在相同的ID,为true跳出判断，不能用return，不然会跳出循环。为false追加进权限数组里
          const ss = this.form.permission_id.in_array(roleid)
          if (ss === true) {
            continue
          } else {
            this.form.permission_id.push(roleid)
          }
        }
        // 假设val为true(全选状态)，就把权限ID追加（push）进permission_id[]数组里；否则为空
        this.form.permission_id = val ? this.form.permission_id : []
      },

      /* 单选 */
      CheckedRolesChange(value) {
        //选中的值
        this.checkedRoles = value
        // 判断假如单选的长度与权限列表长度一致则为true显示勾，否则为false
        const checkedCount = value.length
        this.checkAll = checkedCount === this.rolesList.length
        // 点击单选时，判断选择的权限数组里是否存在这个id,没有则添加，取消钩子要从数组里删除该权限
        const roleid = []
        for (let i = 0; i < value.length; i++) {
          roleid.push(value[i].id)
        }
        this.form.permission_id = roleid
      },
      //获取分页列表
      roleList() {
        let params = {
          "page": this.startpage,
          "limit": this.pageSize
        }
        //调用后台提供的接口方法
        this.$api.roleList(params).then(res => {
          if (res.data.level == "success") {
            this.formdata = res.data.data
            this.totalusers = res.data.page_info.total
            this.loading = false
          } else {
            this.$message.error(res.data.message)
            this.loading = false
          }

        })
      },
      //分页 pageChange当前页发生改变触发函数
      async pageChange(page) {
        this.startpage = page
        this.loading = true
        //调用获取列表的方法
        this.roleList()
      },
      addmodel() {
        this.modelMsg = true
        this.title = '添加角色信息'
        this.addORupdate = "添加",
          this.vshow = false
        this.form.id = "",
          this.form.display_name = "",
          this.form.description = "",
          /* this.form.display_name = "" */
          this.form.permission_id = []
        this.checkedRoles = []

      },
      //提交店铺入驻申请
      async addMsg(form) {
        console.log(form)
        //判断带星号的是否为空
        if ((form.display_name && form.permission_id) == "") {
          this.$message({
            message: "带星号为必填项，请完善信息！",
            type: "warning"
          })
          return false;
        }

        /* 显示加载中。。。 */
        const loadingOne = this.$loading({
          lock: true,
          text: '保存中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        if (form.id > 0) {
          /* 修改 */

          console.log(form)
          await this.$api.setRole(form).then(res => {
            console.log(res)
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.roleList()
              loadingOne.close()
              this.modelMsg = false
            } else {
              this.modelMsg = true
              loadingOne.close()
            }

          })
        } else {
          /* 添加 */
          await this.$api.setRole(form).then(res => {
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.roleList()
              loadingOne.close()
              this.modelMsg = false
            } else {
              this.modelMsg = true
              loadingOne.close()
            }

          })
        }
        this.modelMsg = false

      },
      //修改弹出框
      async updateMsg(row) {
        console.log(row)
        this.modelMsg = true
        this.title = '修改角色信息'
        this.addORupdate = "修改",
          this.vshow = true
        this.form.id = row.id,
          this.form.display_name = row.display_name,
          /*  this.form.display_name = row.display_name, */
          this.form.description = row.description

        const dataid = {
          'id': row.id
        }
        let roleids = []
        await this.$api.roleSet(dataid).then(res => {
          roleids = res.data.data.permission_id
        })

        // 判断查询出来的角色权限的长度是否等于所有权限列表，相等则checkAll为true，勾选全选状态，否则勾选已有的几项
        if (roleids.length === this.rolesList.length) {
          this.checkAll = true
          this.handleCheckAllChange(true)
        } else {
          console.log('查询出来的角色权限的长度不等于所有权限列表，并切不勾选全部')
          this.checkAll = false
          this.handleCheckAllChange(false)
          const roleObj = []
          // 根据更新设入的权限id数组并遍历出来和遍历出总权限数组，两个通过冒泡排序方式对比，有相等的id赋值给复选框进行勾选
          for (let j = 0; j < roleids.length; j++) {
            for (let i = 0; i < this.rolesList.length; i++) {
              const rolesListid = this.rolesList[i].id
              if (roleids[j] === rolesListid) {
                roleObj.push(this.rolesList[i])
                this.CheckedRolesChange(roleObj)
              }
            }
          }

        }
      },
      //删除店铺信息
      async delMsg(id) {
        let delid = {
          id: id
        }
        await this.$confirm('此操作将永久删除该店铺信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const loadingOne = this.$loading({
            lock: true,
            text: '保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.$api.delRole(delid).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            if (res.data.level == "success") {
              loadingOne.close()
              this.roleList()
            } else {
              this.$message.error(res.data.message)
              loadingOne.close()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    }
  }
</script>
<style scoped="scoped">
  /deep/.el-card__header {
    background-color: #409EFF;
    color: whitesmoke;
  }

  /deep/.el-dialog {
    margin-top: 5px !important;
    width: 60%;
  }

  .msgDiv {
    width: 75%;
    margin: auto;
    text-align: center;
  }

  .el-input {
    width: 60%;
    display: flex;
    flex-grow: <2>;
  }
</style>
